//
//  YCIntTextField.m
//  DemoCustomTxtFld
//
//  Created by tangkexiong on 16/3/4.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCIntTextField.h"

@implementation YCIntTextField

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self _configView];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self _configView];
}

- (void)_configView {
    self.keyboardType = UIKeyboardTypeNumberPad;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_textDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc {
    self.keyboardType = UIKeyboardTypeNumberPad;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [self setText:self.text];
}

- (void)setText:(NSString *)text {
    [super setText:[self _convertToInt:text]];
}

#pragma mark - NSNotification

- (void)_textDidChange:(NSNotification *)notifiction {
    [self setText:self.text];
}

- (NSString *)_convertToInt:(NSString *)str {
    NSString *strTemp = [[str componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];
    if ([strTemp isEqualToString:@"0"]) {
        return strTemp;
    } else {
        NSInteger count = strTemp.length;
        NSString *result = @"";
        for (int i = 0; i < count; i++) {
            if (![[strTemp substringWithRange:NSMakeRange(i, 1)] isEqualToString:@"0"]) {
                result = [strTemp substringFromIndex:i];
                break;
            }
        }
        return result;
    }
}

@end